# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.core.urlresolvers import reverse

from diffprices.attributInProduct import searchProductsByAttr
from diffprices.services import UrlParsing, getProducts, getOwners, special_prices, getFiltrUrl
from service.services import currency_rate


def view(request):
    """
    Main page of service comparison price

    :param request: http parameters
    :return: show page of price comparison
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        context = {}
        if request.method == "GET":
            if request.GET:
                products, filt = getProducts(request.GET)
                sort = ''
                if request.GET.has_key('sorting'):
                    sort = request.GET['sorting']
                    sort = '' if sort == '-' else '-'
                context = {'currency': currency_rate, "admin": True, 'products': products, 'filter': filt,
                           'sorting': sort, 'filter_url': getFiltrUrl(filt),
                           'owners': getOwners(), 'special_prices': special_prices}
        if not context:
            context = {'currency': currency_rate, "admin": True, 'products': getProducts(), 'owners': getOwners(),
                       'special_prices': special_prices}
        return render_to_response('diffprices/view.html', context, context_instance=RequestContext(request))
    return HttpResponseRedirect(reverse('home'))


def updateData(request):
    """
    Parsing davilki.

    :param request: http parametrs
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        parser = UrlParsing(True)
        parser.definitionParser()
        #        parser = UrlParsing(False)
        #        parser.definitionParser()
        return HttpResponse('ok')
    return HttpResponseRedirect(reverse('home'))


def search_attr(request):
    """
    Controller of search available attribute in products magento.

    :param request: accept only POST with parameter attrName, where it is code of search attribute
    :return: list of products where is attribute with code attrName
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.method == 'POST':
            return render_to_response('diffprices/attrProducts.html',
                    {'products': searchProductsByAttr(request.POST['attrName'])})
        return render_to_response('diffprices/attrProducts.html')
    return HttpResponseRedirect(reverse('home'))